package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;

    /**
     * 新增报警规则
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void deviceDataAlertFilter() {
        // 1、查询所有的规则
        List<AlertRule> alertRules = alertRuleMapper.selectByFunctionId(null,null,null);
        if (CollUtil.isEmpty(alertRules)){
            log.info("没有需要处理的报警规则");
            return;
        }
        // 2、查询所有设备上报的最新数据  从Redis中查询
        List<Object> values = redisTemplate.boundHashOps(CacheConstants.DEVICE_LASTDATA_CACHE_KEY).values();
        if (CollUtil.isEmpty(values)){
            log.info("没有需要处理的设备数据");
            return;
        }
        // 3、数据格式标准化处理  List<DeviceDataVo>
        List<DeviceDataVo> allDeviceDataVoList = new ArrayList<>();
        for (Object value : values) {
            List<DeviceDataVo> deviceDataVoList = JSONUtil.toList(value.toString(), DeviceDataVo.class);
            allDeviceDataVoList.addAll(deviceDataVoList);
        }
        // 4、一条条数据做处理
        for (DeviceDataVo deviceDataVo : allDeviceDataVoList) {
            deviceDataAlert(deviceDataVo);
        }
    }

    @Autowired
    private ScriptEngine scriptEngine;

    private void deviceDataAlert(DeviceDataVo deviceDataVo) {

        // 1、保证现在处理的是新数据  保证数据是1分钟之内的数据
        if (LocalDateTimeUtil.between(deviceDataVo.getAlarmTime(), LocalDateTime.now(), ChronoUnit.MINUTES) > 1){
            log.info("数据不是1分钟之内的数据，直接跳过");
            return;
        }
        // 2、查询此数据对应的规则  407-1
        List<AlertRule> alertRuleWithDeviceList = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        List<AlertRule> alertRuleWithAllDeviceList = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        // 3、合并规则
        alertRuleWithDeviceList.addAll(alertRuleWithAllDeviceList);
        if (CollUtil.isEmpty(alertRuleWithDeviceList)){
            log.info("没有需要处理的报警规则");
            return;
        }
        // 4、遍历每一条规则
        for (AlertRule alertRule : alertRuleWithDeviceList) {
            log.info("开始进入四层校验。。。。。。。。。。。。。。");
            log.info("第一层开始。。。。。。。。。。。。。。");
            // 判断上报时间是否在生效时间区间之内
            LocalTime localTime = deviceDataVo.getAlarmTime().toLocalTime();
            String[] split = alertRule.getAlertEffectivePeriod().split("~");
            // split[0];    split[1] localTime
            if (localTime.isBefore(LocalTime.parse(split[0])) || localTime.isAfter(LocalTime.parse(split[1]))){
                log.info("上报时间不在生效时间区间之内，直接跳过");
                continue;
            }
            log.info("第一层结束。。。。。。。。。。。。。");
            log.info("第二层开始。。。。。。。。。。。。。");
            // 检验上报的数据80是否到达阈值 alertRule.getValue()
            String expression = deviceDataVo.getDataValue()+alertRule.getOperator()+alertRule.getValue();  //  "80>=100"
            // 从Redis中获取报警次数
            String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX +
                    deviceDataVo.getIotId() + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
            try {
                Boolean isReach = Boolean.parseBoolean(scriptEngine.eval(expression).toString());
                if (isReach){
                    log.info("第三层开始。。。。。。。。。。。。。");
                    // Redis中查询沉默周期
                    String silentCacheKey = CacheConstants.ALERT_SILENT_PREFIX + deviceDataVo.getIotId() + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
                    //redisTemplate.boundValueOps(silentCacheKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
                    if (redisTemplate.hasKey(silentCacheKey)) {
                        log.info("有沉默周期，暂时不报警");
                        continue;
                    }
                    log.info("第四层开始。。。。。。。。。。。。。");

                    String count = redisTemplate.boundValueOps(aggCountKey).get();
                    Integer currentCount = StrUtil.isBlank(count)?1:Integer.parseInt(count)+1;
                    // 判断是否到达持续周期
                    if (currentCount==alertRule.getDuration()){
                        redisTemplate.boundValueOps(aggCountKey).set(currentCount+"");
                        continue;
                    }

                    // 到达报警次数
                    redisTemplate.delete(aggCountKey);
                    // 放入沉默周期
                    redisTemplate.boundValueOps(silentCacheKey).set("",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
                    //插入规则报警数据
                    insertAlertData(alertRule,deviceDataVo);
                }else {
                    log.info("上报的数据没有到达阈值，直接跳过");

                    redisTemplate.delete(aggCountKey);
                }
            } catch (ScriptException e) {
                log.info("上报的数据没有到达阈值，直接跳过");

                redisTemplate.delete(aggCountKey);
            }
        }



    }

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private AlertDataMapper alertDataMapper;
    //设备维护人员的角色名称
    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    //超级管理员的角色名称
    @Value("${zzyl.alert.managerRole}")
    private String managerRole;



    // 直接拷贝
    private void insertAlertData(AlertRule alertRule,DeviceDataVo deviceDataVo) {
        //获取消息的消费者
        List<Long> consumerIds = null;
        if (ObjectUtil.equals(0, alertRule.getAlertDataType())) {
            //如果是老人报警数据，需要通知绑定老人的护理员。根据iotId查询老人绑定的护理员
            if(deviceDataVo.getLocationType() == 0){
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceDataVo.getIotId());
            }else if(deviceDataVo.getLocationType() == 1 && deviceDataVo.getPhysicalLocationType() == 2){
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceDataVo.getIotId());
            }
        } else {
            //如果是设备报警数据，需要通知设备维护人员。根据指定角色名称查询相关用户
            consumerIds = userRoleMapper.selectUserIdsByRoleName(deviceMaintainerRole);
        }
        //查询超级管理员，超级管理员无论什么消息都会接收
        List<Long> managerIds = userRoleMapper.selectUserIdsByRoleName(managerRole);
        List<Long> allConsumerIds = CollUtil.addAllIfNotContains(consumerIds, managerIds);
        allConsumerIds = CollUtil.distinct(allConsumerIds);

        log.error("通知的人员有："+allConsumerIds);
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = consumerIds.stream().map(id -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataMapper.batchInsert(list);
    }

}
